package com.example.mytodo

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.core.graphics.toColor
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import kotlinx.android.synthetic.main.fragment_todo.*
import kotlinx.android.synthetic.main.todo_item.*
import org.w3c.dom.Text
import java.util.*
import kotlin.collections.ArrayList


class TodoFragment : Fragment() {

    val TAG = "@@TodoFragment"

    lateinit var helper:DBHelper
    lateinit var adapter: TodoAdapter

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        return inflater.inflate(R.layout.fragment_todo, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        Log.d(TAG,"onViewCreated")
        init()

    }

    private fun init() {
        helper = DBHelper(context,"todo",1)
        adapter = TodoAdapter()

        recycler_todo.adapter = adapter
        recycler_todo.layoutManager = LinearLayoutManager(context)
        readInDB()

        btn_new_todo.setOnClickListener {
            val intent = Intent(context,NewTodoActivity::class.java)
            startActivity(intent)
        }
    }


    inner class TodoAdapter: RecyclerView.Adapter<TodoViewHoler>() {

        private val data = arrayListOf<Atodo> ()

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TodoViewHoler {
            val view = LayoutInflater.from(parent.context).inflate(R.layout.todo_item,parent,false)
            return  TodoViewHoler(view).apply {
                id = view.findViewById(R.id.todo_id)
                todostring = view.findViewById(R.id.todo_1)
                todotime = view.findViewById(R.id.todo_time)
                btnUpdate = view.findViewById(R.id.btn_toupdate)
                btnDelete = view.findViewById(R.id.btn_todelete)
                btnSet = view.findViewById(R.id.btn_toset)

                bk = view.findViewById(R.id.todo_frame)
            }
        }

        override fun onBindViewHolder(holder: TodoViewHoler, position: Int) {

            holder.render(data[position])
        }

        override fun getItemCount(): Int {
            return data.size
        }

        fun setData(arr: ArrayList<Atodo>) {
            data.addAll(arr)
            notifyDataSetChanged()
        }


    }

    inner class TodoViewHoler(view:View):RecyclerView.ViewHolder(view) {

        var id: TextView? = null
        var todostring: TextView? = null
        var btnDelete: ImageButton? = null
        var btnUpdate: ImageButton? = null
        var btnSet: ImageButton? = null
        var bk: View? = null
        var todotime: TextView? = null

        fun render (todo:Atodo){
            if(todo.state == 1) {
               bk?.setBackgroundColor(Color.parseColor("#DEDEDE"))
            }
            id?.text = todo.id.toString()
            todotime?.text= Date(todo.addtime).toString()
            todostring?.text  = todo.todoString
            btnDelete?.setOnClickListener{
                println("to delete ")
                AlertDialog.Builder(requireContext())
                    .setTitle("请确认").setMessage("确定要删除吗")
                    .setNegativeButton("取消"){d,w->
                        Toast.makeText(context,"已取消", Toast.LENGTH_LONG).show()
                    }
                    .setPositiveButton("确定"){d,w->
                        Log.d(TAG,"to delete id = ${todo.id}")
                        val db = helper.writableDatabase
                        db.delete(Atodo.TABLE,"id = ?",arrayOf(todo.id.toString()))
                        reStart()
                        Toast.makeText(context,"删除成功" , Toast.LENGTH_LONG).show()
                    }
                    .show()

            }
            btnUpdate?.setOnClickListener {

                val intent = Intent(context,EditTodoActivity()::class.java)
                intent.putExtra("idx",todo.id)
                startActivity(intent)
              }
            btnSet?.setOnClickListener {
                val db = helper.writableDatabase
                todo.state = 1
                db.execSQL("update ${Atodo.TABLE} set ${Atodo.T_STATE} = 1 where ${Atodo.T_ID} = ${todo.id}").toString()
                Log.d(TAG,"${todo.id} de state is ${todo.state}")
                reStart()
            }
        }
    }

    @SuppressLint("Range")
    private fun readInDB()  {
        val db = helper.readableDatabase
        val cursor = db.query(Atodo.TABLE,null,null,null,null,null,
            "${Atodo.T_ID} desc")
        val arr = arrayListOf<Atodo>()
        if(cursor.moveToFirst()){
            do{
                arr.add(
                    Atodo(
                        cursor.getString(cursor.getColumnIndex(Atodo.T_TODOSTRING)),
                        cursor.getLong(cursor.getColumnIndex(Atodo.T_TIME)),
                        cursor.getInt(cursor.getColumnIndex(Atodo.T_STATE)),

                    ).apply {
                        id = cursor.getInt(cursor.getColumnIndex(Atodo.T_ID))
                    }
                )
            }while (cursor.moveToNext())
        }
        adapter.setData(arr)
        cursor.close()
        Log.d(TAG,"$arr")


    }


//    override fun onStart() {
//        super.onStart()
//        Log.d(TAG,"onStart")
//    }
//
//    override fun onResume() {
//        super.onResume()
//        Log.d(TAG,"onResume")
//    }
//
//    override fun onPause() {
//        super.onPause()
//        Log.d(TAG,"onPause")
//    }
//
//    override fun onStop() {
//        super.onStop()
//        Log.d(TAG,"onStop")
//    }
//
//    override fun onDestroyView() {
//        super.onDestroyView()
//        Log.d(TAG,"onDestroyView")
//    }
//
//    override fun onDestroy() {
//        super.onDestroy()
//        Log.d(TAG,"onDestroy")
//    }
//
//    override fun onDetach() {
//        super.onDetach()
//        Log.d(TAG,"onDetach")
//    }

    fun reStart(){
        Log.d(TAG,"to restart")
        val intent = Intent(context,MainActivity()::class.java)
        activity?.finish()
        activity?.startActivity(intent)
    }
}